<?php ob_start();
session_start(); // on relaye la session 
if(isset($_SESSION["is_registered"]) && $_SESSION["is_registered"] == "registered"){
		$enregistrer = $_SESSION["is_registered"];
}else{
	header("location:../../menu.php"); // redirection en cas d'echec
}
	require_once('../../Connections/microassur.php'); 
	require_once('../../utils/fonctions.php');
    require_once('../../include/inc_config.php');	
?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if(isset($_POST['Identifiant_personne']) && !empty($_POST['Identifiant_personne']))
{
	if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form1")) 
	{
		// $tab = explode('-', $_POST['Identifiant_personne']);
        $zSql = " SELECT Identifiant_role FROM role WHERE Identifiant_personne = " . $_POST['Identifiant_personne'] . " AND `Identifiant_offre` IS NULL" ;
        mysql_select_db($database_microassur, $microassur);
        $oResult = mysql_query($zSql, $microassur) ;
        $tiResults = mysql_fetch_assoc($oResult);
        $iNbResult = mysql_num_rows($oResult);
        if ($iNbResult)
        {
            $updateSQL = sprintf("UPDATE `role` SET Identifiant_personne=%s, Identifiant_offre=%s WHERE Identifiant_role=%s",
            				   GetSQLValueString($_POST['Identifiant_personne'], "int"),
            				   GetSQLValueString($_POST['Identifiant_offre'], "int"), 
            				   GetSQLValueString($tiResults['Identifiant_role'], "int"));
        }
        else
        {
            $zSql = " SELECT * FROM role WHERE Identifiant_personne = " . $_POST['Identifiant_personne'] . " AND `Identifiant_offre` = " . $_POST['Identifiant_offre'] ;
            // --- echo $zSql ;
            mysql_select_db($database_microassur, $microassur);
            $oResNbRole = mysql_query($zSql, $microassur) ;
            $tiNbRoles = mysql_fetch_assoc($oResNbRole);
            
            if ($tiNbRoles['Identifiant_role']) 
            {
                // --- ne sert à rien mas juste pour ne pas casser le système
                // --- en gros ce la dit ne rien faire si le role choisi est déjà associé à la personne
                $updateSQL  = " SELECT 1 " ;
            }
            else
            {
                $updateSQL  = " INSERT INTO `role` " ;
                $updateSQL .= " ( Type_role, Etat_role, Type_assure, Identifiant_personne, Identifiant_contrat, Identifiant_offre ) VALUE " ;
                $updateSQL .= " ('P' "  ;
                $updateSQL .= " , 'A' " ;
                $updateSQL .= " , NULL " ;
                $updateSQL .= " , " . GetSQLValueString($_POST['Identifiant_personne'], "int") ;
                $updateSQL .= " , " . GetSQLValueString($tiNbRoles['Identifiant_contrat'], "int") ;
                $updateSQL .= " , " . GetSQLValueString($_POST['Identifiant_offre'], "int") . ")" ;
                
                // --- echo $updateSQL ;
            }
        }
        
        mysql_select_db($database_microassur, $microassur);
        mysql_query("START TRANSACTION");
        $Result1 = mysql_query($updateSQL, $microassur) or die(mysql_error());
        if($Result1){
        	mysql_query("commit");
        	//$message = colorer("Rattachement offre effectué.","true");
                $message = colorer("L’offre est désormais rattachée au partenaire.","true");
        		// $deleteGoTo = "../../menu.php"; //$deleteGoTo = "../../menu.php?msg=rattacheOffre";
        		// header(sprintf("Location: %s", $deleteGoTo));
        	unset($_POST);
        }else{
        	mysql_query("rollback");
        	$message = colorer("Problème modification rôle partenaire, contactez la DSI.","false");
        }
            
	}
}else { $message = colorer("","false"); }

mysql_select_db($database_microassur, $microassur);
$query_rs_personne = "SELECT DISTINCT personne.* FROM personne, role WHERE personne.Identifiant_personne = role.Identifiant_personne AND role.Type_role='P' ORDER BY Raison_sociale "; //"SELECT * FROM personne";
$rs_personne = mysql_query($query_rs_personne, $microassur) or die(mysql_error());
$row_rs_personne = mysql_fetch_assoc($rs_personne);
$totalRows_rs_personne = mysql_num_rows($rs_personne);

mysql_select_db($database_microassur, $microassur);
$query_rs_offre = "SELECT * FROM offre  WHERE ((TO_DAYS(Date_fin_offre) - TO_DAYS(NOW()) >= 0) OR  Date_fin_offre IS NULL) AND (TO_DAYS(NOW()) - TO_DAYS(Date_debut_offre) >= 0) "; 
//$query_rs_offre = "SELECT * FROM offre";
$rs_offre = mysql_query($query_rs_offre, $microassur) or die(mysql_error());
$row_rs_offre = mysql_fetch_assoc($rs_offre);
$totalRows_rs_offre = mysql_num_rows($rs_offre);
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=8" />
			<title>Rattachement offre</title>
			<link rel="stylesheet" type="text/css" href="../../css/main.css" />
            <link rel="stylesheet" type="text/css" href="list.css" />
			<!--[if IE 7]>
            	<link rel="stylesheet" type="text/css" href="../../css/ie7.css" />
            	<link rel="stylesheet" type="text/css" href="form_ie7.css" />
            <![endif]-->
	        <style type="text/css">
<!--
.Style1 {font-size: 16px}
-->
            </style>
</head>
<body>
<div id="sf_menu1">
	<h3>Partenaire</h3>
<?php
	if(isset($message) && !empty($message)){
		echo $message;
	}
	$nommodule="Rattachement de l'offre";
	//$nommodule2="Liste des partenaires";
	$nom_module_saisie="Rattachement de l'offre";
?>
</div>
<div class="cleared"></div>

<div class="corps1">
<!--/***************************************/-->

<form action="<?php echo $editFormAction; ?>" method="post" name="form1" id="form1">
	<div class="imgleft"></div>
	<div class="imgmiddle">
    <div class="btn">
    	<span class="btnleft"></span>
        <span class="btnmiddle">
        	<h5><?php echo $nommodule; ?></h5>
        </span><span class="btnright"></span>
    </div>
  	<div class="btn1">
    	<span class="btnleft"></span>
        <span class="btnmiddle">
        	<h5><?php echo $nom_module_saisie; ?></h5>
        </span>
        <span class="btnright"></span>
    </div>
	<div class="formulaire">
  <table class="tabform rattach">
    <tr>
      <td class="td1">OFFRE</td>
      <td>
      <select name="Identifiant_offre" class="rattach">
        <?php 
do {  
?>
        <option value="<?php echo $row_rs_offre['Identifiant_offre']?>" <?php if (!(strcmp($row_rs_offre['Identifiant_offre'], htmlentities(@$row_rs_mod['Identifiant_offre'], ENT_COMPAT, 'utf-8')))) {echo "SELECTED";} ?>><?php echo $row_rs_offre['Libelle_offre']?></option>
        <?php
} while ($row_rs_offre = mysql_fetch_assoc($rs_offre));
?>
      </select>
      </td>
    </tr>
    <tr> </tr>
    <tr>
      <td class="td1">PARTENAIRE</td>
      <td><select name="Identifiant_personne" class="rattach">
        <?php 
do {  
?>
        <option value="<?php echo $row_rs_personne['Identifiant_personne']; ?>"><?php echo $row_rs_personne['Raison_sociale']?></option>
		
        <?php
} while ($row_rs_personne = mysql_fetch_assoc($rs_personne));
?>
      </select>
      </td>
    </tr>
  </table>
    </div>
</div>
<div class="imgright"></div>				
<div class="cleared"></div>

<div class="bt1">
	<a href="../../menu.php">
    	<span class="btleft"></span>
        <span class="btmiddle">Retour</span>
        <span class="btright"></span>
    </a>
</div>

<div class="bt">
	<a href="../../menu.php">
    	<span class="btleft"></span>
        <span class="btmiddle">Annuler</span>
        <span class="btright"></span>
    </a>
</div>
<div class="bt">
	<span class="btleft"></span>
    <input type="submit" name="Valider" value="Valider" class="resizeall btmiddle"/>
    <span class="btright"></span>
</div>
    
<div class="cleared"></div>

  <input type="hidden" name="MM_update" value="form1" />
</form>
 </div>
</body>
</html>
<?php

mysql_free_result($rs_personne);

mysql_free_result($rs_offre);
ob_end_flush();
?>